<?php
/**
 * Created by PhpStorm.
 * User: xiangfeng
 * Date: 2022/4/10
 * Time: 3:41 PM
 */

namespace app\api\service;


use app\api\http\exceptions\ApiErr;
use app\api\http\exceptions\ApiExceptions;
use app\api\model\UserFollowModel;
use app\api\model\UserModel;
use think\Service;

/**
 * 关注
 * Class UserFollowService
 * @package app\api\service
 */
class UserFollowService extends Service
{
    /**
     * 查询关注记录
     * @param array $where
     * @return array
     */
    public static function get(array $where): array
    {
        $data = UserFollowModel::mk()->where($where)->findOrEmpty();
        return !empty($data) ? $data->toArray() : [];
    }

    /**
     * 查询我的好友
     * @param int $user_id
     * @return array
     */
    public static function getFocusUserIds(int $user_id): array
    {
        $where = [
            ['follow_status', '=', 1],//状态(0/待处理 1/同意 2/拒绝)
            ['user_id', '=', $user_id],
            ['delete_time', '=', 0],
        ];
        $where1 = [
            ['follow_status', '=', 1],//状态(0/待处理 1/同意 2/拒绝)
            ['focus_user_id', '=', $user_id],
            ['delete_time', '=', 0],
        ];
        $data = UserFollowModel::mk()->field('focus_user_id')->where($where)->column('focus_user_id');//我加好友
        $data1 = UserFollowModel::mk()->field('user_id')->where($where1)->column('user_id');//被加好友
        return array_reverse(array_merge($data, $data1));
    }

    /**
     * 加好友
     * @param array $param
     * @return bool
     * @throws ApiExceptions
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function addUserFollow(array $param): bool
    {
        $row = UserService::checkUserIsExist((int)$param['focus_user_id']);
        if (!$row) throw new ApiExceptions(ApiErr::USER_FRIEND_NO_EXIST);
        $data = self::isFollowFriend($param['user_id'], $param['focus_user_id'], 1);
        if ($data) throw new ApiExceptions(ApiErr::USER_ALREADY_JOIN_FRIEND);
        //小程序通知给好友
        $param['create_time'] = time();
        return UserFollowModel::mk()->insert($param);
    }

    /**
     * 粉丝申请处理
     * @param int $user_id
     * @param int $id 关注记录ID
     * @param int $status 状态（1/同意 2/拒绝）
     * @return bool
     * @throws ApiExceptions
     */
    public static function auditFriendApply(int $user_id, int $id, int $status): bool
    {
        $where = [
            'focus_user_id' => $user_id,
            'id' => $id,
            'follow_status' => 0,
            'delete_time' => 0,
        ];
        $data = self::get($where);
        if (empty($data)) throw new ApiExceptions(ApiErr::USER_FRIEND_FOLLOW_NO_EXIST);
        $update_param = [
            'follow_status' => $status == 1 ? 1 : 2,
            'update_time' => time(),
            'cancel_time' => $status == 2 ? time() : 0,
            'delete_time' => $status == 2 ? time() : 0
        ];
        $row = UserFollowModel::mk()->where(['id' => $id])->save($update_param);
        if (!$row) throw new ApiExceptions(ApiErr::UPDATE_DB_FAILED);
        //小程序通知给粉丝
        return $row;
    }

    /**
     * 获取好友待处理列表
     * @param array $page_config
     * @param int $focus_user_id
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public static function getFriendApplyList(array $page_config, int $focus_user_id)
    {
        $field = 'id,user_id';
        $where = [
            'focus_user_id' => $focus_user_id,
            'follow_status' => 0,
            'delete_time' => 0,
        ];
        $data = UserFollowModel::mk()->where($where)->order('id desc')->field($field)->paginate($page_config)->each(function ($item) {
            $field = 'uname,avatar,image_list,introduce,certification_status,working_unit,join_year,college_dep_name,college_name';
            $user = UserModel::mk()->where(['id' => $item['user_id']])->field($field)->findOrEmpty();
            $item['uname'] = !empty($user['uname']) ? $user['uname'] : '';
            $item['avatar'] = !empty($user['avatar']) ? $user['avatar'] : '';
            $item['college_name'] = !empty($user['college_name']) ? $user['college_name'] : '';
            $item['college_dep_name'] = !empty($user['college_dep_name']) ? $user['college_dep_name'] : '';
            $item['image_list'] = !empty($user['image_list']) ? json_decode($user['image_list'], true) : [];
            $item['introduce'] = !empty($user['introduce']) ? $user['introduce'] : '';
            $item['certification_status'] = !empty($user['certification_status']) ? $user['certification_status'] == 1 ? '已认证' : '未认证' : '未认证';
            $item['working_unit'] = !empty($user['working_unit']) ? $user['working_unit'] : '';
            $item['join_year'] = !empty($user['join_year']) ? $user['join_year'] : '';
            return $item;
        });
        return $data;
    }

    /**
     * 是否加该好友
     * @param int $user_id 当前登录用户ID
     * @param int $focus_user_id 好友用户ID
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function isFollowFriend(int $user_id, int $focus_user_id, int $tag = 0): bool
    {
        //如果自己加自己默认已经是好友
        if ($user_id == $focus_user_id && $user_id > 0 && $focus_user_id > 0) return true;
        //当前登录用户是发起关注用户查询时
        $where = [
            ['user_id', '=', $user_id],
            ['focus_user_id', '=', $focus_user_id],
            ['delete_time', '=', 0],
            $tag == 1 ? ['follow_status', '<', 2] : ['follow_status', '=', 1],
        ];
        $data = UserFollowModel::mk()->field('id')->where($where)->find();
        if (!empty($data)) return true;
        //当前登录用户是被关注用户查询时
        $where1 = [
            ['user_id', '=', $focus_user_id],
            ['focus_user_id', '=', $user_id],
            ['delete_time', '=', 0],
            $tag == 1 ? ['follow_status', '<', 2] : ['follow_status', '=', 1],
        ];
        $data = UserFollowModel::mk()->field('id')->where($where1)->find();
        return !empty($data) ? true : false;
    }
}